package net.htjs.mobile.qxoa;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import net.htjs.mobile.qxoa.apn.util.ApnUtility;
import net.htjs.mobile.qxoa.db.DatabaseHandler;
import net.htjs.mobile.qxoa.db.UserInfo;
import net.htjs.mobile.qxoa.gw.Myinfodata;
import net.htjs.mobile.qxoa.util.L;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class LoginActivity extends Activity {
	private Button login,yzmButton;
	EditText userN;
	EditText pssW;
	EditText yzm;
	CheckBox recorduserinfo;
	
	public static Integer yzmINT = 00000;
	private static String TAG = "LoginActivity";
	DatabaseHandler dbh;
	static boolean isRecordUserInfo = false;

	// APN相关
	private ApnUtility apnutility = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);

		userN = (EditText) this.findViewById(R.id.username_edit);
		pssW = (EditText) this.findViewById(R.id.password_edit);
		yzm = (EditText) this.findViewById(R.id.yzm_edit);
		// APN相关
		apnutility = new ApnUtility(this);
		
		dbh = new DatabaseHandler(this);
		if (!dbh.userTableIsExist()) {
			try {
				dbh.onCreate(dbh.getWritableDatabase());
			} catch (Exception e) {

			}
		}
		
		List<UserInfo> uis = dbh.getAllUserInfos();
		UserInfo userinfo = null;
		if (uis.size() != 0) {
			for (UserInfo ui : uis) {
				System.out.println(ui.toString());
			}
			userinfo = uis.get(uis.size() - 1);
		}
		String userId="";
		String password="";
		if (userinfo == null) {
			userN.setText(userId);
			pssW.setText(userId);
		} else {
			userId=userinfo.getName();
			password=userinfo.getPassword();
			userN.setText(userId);
			pssW.setText(password);
		} 
		recorduserinfo = (CheckBox) findViewById(R.id.recorduserinfo);
		if(!"".equals(password)){
			recorduserinfo.setChecked(true);
		}else{
			recorduserinfo.setChecked(false);
		}
		recorduserinfo .setOnCheckedChangeListener(new
		   CompoundButton.OnCheckedChangeListener() { 
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //
					if (isChecked) { 
						isRecordUserInfo = true; 
						} else { 
							isRecordUserInfo = false;
						}
					}
			});
		
		login = (Button) this.findViewById(R.id.signin_button);
		
		login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if("".equals(yzm.getText().toString().trim())){
					AlertDialog.Builder builder = new Builder(
							LoginActivity.this);
					builder.setTitle("提示");
					builder.setMessage("验证码为空");
					Dialog dialog = builder.create();
					builder.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialog,
										int whichButton) {
									// 这里添加点击确定后的逻辑
									dialog.dismiss();
								}
							});

					builder.create().show();
					return;
				}
				if(!yzm.getText().toString().trim().equals(yzmINT.toString())){
					AlertDialog.Builder builder = new Builder(
							LoginActivity.this);
					builder.setTitle("提示");
					builder.setMessage("验证码校验失败");
					Dialog dialog = builder.create();
					builder.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialog,
										int whichButton) {
									// 这里添加点击确定后的逻辑
									dialog.dismiss();
								}
							});

					builder.create().show();
					return;
				}
				L.C.loginFlag = false;
				L.C.startLoginTime = System.currentTimeMillis();
				L.C.isLoginTimeOut = false;
				final ProgressDialog pdialog = ProgressDialog.show(
						LoginActivity.this, "", "登录中...", true);
				new Thread(new Runnable() {

					public void run() {

						Looper.prepare();
						while (true) {
							if (L.C.loginFlag) {
								break;
							}
							long timeNow = System.currentTimeMillis();
							if (timeNow - L.C.startLoginTime > L.C.MAXTIMETOLOGIN) {
								pdialog.dismiss();
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);

								builder.setTitle("提示");
								builder.setIcon(R.drawable.logonyoa);
								builder.setMessage("连接超时");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												L.C.isLoginTimeOut = true;// 确定连接超时
												dialog.dismiss();
											}
										});

								builder.create().show();
								break;
							} else {
								try {
									Thread.sleep(1000l);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						}
						Looper.loop();
					}

				}).start();
				new Thread(new Runnable() {

					public void run() {
						Looper.prepare();
						
						HttpPost request = new HttpPost(L.loginUrl + "userId="
								+ userN.getText().toString().trim()
								+ "&password="
								+ pssW.getText().toString().trim());
						// 先封装一个 JSON 对象 /server/3g/login4Mobile.jsp
						JSONObject param = new JSONObject();
						try {
							param.put("userId", userN.getText().toString()
									.trim());
							param.put("password", pssW.getText().toString()
									.trim());
							
							// 绑定到请求 Entry
							StringEntity se = new StringEntity(param.toString());
							request.setEntity(se);
							// 发送请求
							DefaultHttpClient client = new DefaultHttpClient();
							HttpResponse httpResponse = client.execute(request);
							L.C.loginFlag = true;

							// 如果超时，不做任何操作
							if (L.C.isLoginTimeOut) {
								return;
							}
							// 得到应答的字符串，这也是一个 JSON 格式保存的数据
							String retSrc = EntityUtils.toString(httpResponse
									.getEntity());

							List<Cookie> cookies = client.getCookieStore()
									.getCookies();
							if (!cookies.isEmpty()) {
								for (int i = 0; i < cookies.size(); i++) {
									L.cookie = cookies.get(i);
								}
							}
							isRecordUserInfo=recorduserinfo.isChecked();
							// 生成 JSON 对象
							System.out.println(retSrc);
							JSONObject i = new JSONObject(retSrc.trim());
							if ("1".equals(i.get("result"))) {
								
								pdialog.dismiss();
								L.LoginInfo.userName = userN.getText()
										.toString().trim();
								L.LoginInfo.password = pssW.getText()
										.toString().trim();
								
								  if (isRecordUserInfo) { 
									  if (dbh.getUserInfo(L.LoginInfo.userName) != null)
									  { 
										  	updateUserInfo(L.LoginInfo.userName,L.LoginInfo.password);
									  } else {
											recordUserInfo(L.LoginInfo.userName, L.LoginInfo.password); 
									  } 
								} else {
									  dbh.deleteUserInfo(); 
									  recordUserInfo(L.LoginInfo.userName,"");
								}
								 
								
								jumpPage();
							} else if ("4".equals(i.get("result"))) {
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage("非法访问");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});

								builder.create().show();

							} else if ("5".equals(i.get("result"))) {
								//
							} else if ("0".equals(i.get("result"))) {
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);

								builder.setTitle("提示");
								builder.setMessage("账户被禁用");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});

								builder.create().show();
							} else if ("3".equals(i.get("result"))) {
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage("用户名无效");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});

								builder.create().show();
							} else {
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage("密码错误");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});

								builder.create().show();
							}
							L.C.loginFlag = true;

							// 如果超时，不做任何操作
							if (L.C.isLoginTimeOut) {
								return;
							}
						} catch (JSONException e) {
							AlertDialog.Builder builder = new Builder(
									LoginActivity.this);
							builder.setTitle("提示");
							builder.setMessage("登录失败");
							Dialog dialog = builder.create();
							builder.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											// 这里添加点击确定后的逻辑
											dialog.dismiss();
										}
									});

							builder.create().show();
							e.printStackTrace();
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						pdialog.dismiss();
						login.setClickable(true);
						Looper.loop();
					}

				}).start();
			}
		});
		
		yzmButton  = (Button) this.findViewById(R.id.yzm_button);
		
		yzmButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
			 
				L.C.loginFlag = false;
				L.C.startLoginTime = System.currentTimeMillis();
				L.C.isLoginTimeOut = false;
				final ProgressDialog pdialog = ProgressDialog.show(
						LoginActivity.this, "", "获取验证码中...", true);
				 

						 
				new Thread(new Runnable() {

					public void run() {
						Looper.prepare();
						int zcmInt = new java.util.Random().nextInt(99999);
						if(zcmInt<10000){
							zcmInt+=10000;
						}
						System.out.println("+++++++++   "+zcmInt+"   "+L.fdxUrl + "?userId="
								+ userN.getText().toString().trim()
								+ "&yzm="
								+ yzmINT);
						yzmINT = zcmInt;
						HttpPost request = new HttpPost(L.fdxUrl + "?userId="
								+ userN.getText().toString().trim()
								+ "&yzm="
								+ yzmINT);
						// 先封装一个 JSON 对象 /server/3g/login4Mobile.jsp
						JSONObject param = new JSONObject();
						try {
							param.put("userId", userN.getText().toString().trim());
							param.put("yzm", yzmINT);
							// 绑定到请求 Entry
							StringEntity se = new StringEntity(param.toString());
							request.setEntity(se);
							// 发送请求
							DefaultHttpClient client = new DefaultHttpClient();
							HttpResponse httpResponse = client.execute(request);

							// 得到应答的字符串，这也是一个 JSON 格式保存的数据
							String retSrc = EntityUtils.toString(httpResponse.getEntity());

							// 生成 JSON 对象
							System.out.println(retSrc);
							JSONObject i = new JSONObject(retSrc.trim());
							pdialog.dismiss();
							if ("1".equals(i.get("result"))) {//表示发送成功
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage("发送验证码成功");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});
								builder.create().show();
								
							} else if ("2".equals(i.get("result"))) {//代表没有绑定手机号
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage(i.get("msg")+"");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});
								builder.create().show();
							} else if ("0".equals(i.get("result"))) {//表示发送失败
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage(i.get("msg")+"");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});
								builder.create().show();
							} else {//其他异常
								AlertDialog.Builder builder = new Builder(
										LoginActivity.this);
								builder.setTitle("提示");
								builder.setMessage(i.get("msg")+"");
								Dialog dialog = builder.create();
								builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int whichButton) {
												// 这里添加点击确定后的逻辑
												dialog.dismiss();
											}
										});
								builder.create().show();
							}
							
						} catch (JSONException e) {
							AlertDialog.Builder builder = new Builder(
									LoginActivity.this);
							builder.setTitle("提示");
							builder.setMessage("获取验证码失败");
							Dialog dialog = builder.create();
							builder.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											// 这里添加点击确定后的逻辑
											dialog.dismiss();
										}
									});

							builder.create().show();
							e.printStackTrace();
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						pdialog.dismiss();
						login.setClickable(true);
						Looper.loop();
					}

				}).start();
			}
		});

	}
	public void updateApp(Myinfodata myinfo){
		 
		Uri uri = Uri.parse(myinfo.DownUrl);
		Intent it = new Intent(
				Intent.ACTION_VIEW, uri);
		startActivity(it);
	}
	 

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
 

	public boolean jumpPage() {
		Intent mainIntent = new Intent(getApplication(), TabMainActivity.class);
		super.finish();
		startActivity(mainIntent);
		return true;
	}

	public boolean recordUserInfo(String userName, String password) {
		dbh.addUserInfo(new UserInfo().setName(userName).setPassword(password));
		return true;
	}

	public boolean updateUserInfo(String userName, String password) {
		dbh.updateUserInfo(new UserInfo().setName(userName).setPassword(
				password));
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				if(L.isUseAPN)apnutility.StopYidongApn();
				super.finish();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	public void finish() {
 
		if(L.isUseAPN)apnutility.StopYidongApn();
		super.finish();
	}
}